Skip to content

fix(logging): stop adding log handlers on every get_logger() call - #158

Open
tkislan wants to merge 3 commits into
mainfrom
tk/fix-duplicate-log-handlers
Open

tkislan wants to merge 3 commits into
mainfrom
tk/fix-duplicate-log-handlers

Conversation

@tkislan

@tkislan tkislan commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

LoggerManager is a singleton, but __init__ returned early only when the requested level differed from the current one. Every call at the same level ran _create_logger() and _configure_error_handler() again, adding another FileHandler (a stdout StreamHandler under CI) and another WebappErrorHandler to the shared file_logger logger.

About ten modules fetch the logger at import time, and sql/duckdb_sql.py, variable_explorer.py and set_notebook_path.py fetch it on each use. On main:

FileHandler WebappErrorHandler
after import deepnote_toolkit.cli.server 10 10
after 5 more LoggerManager().get_logger() calls 15 15
this branch, at both points 1 1

__init__ now returns whenever the manager is initialized, after updating the level if it changed.

Impact on main

  • Every record is written to helpers.log once per handler, so ten or more times in a kernel.
  • Every ERROR record is posted to the webapp once per WebappErrorHandler. Each post makes up to three attempts with a 5 s timeout, so while the endpoint hangs, one ERROR can block the logging thread for about 16 s per copy. This figure comes from reading the code; I didn't measure it.
  • Each extra FileHandler keeps a file descriptor open for the life of the process.

Behavior changes

  • log_file is ignored after the first call. Before, a later call at the same level with a different path added a handler for that path, and a call at a different level ignored it. No caller passes log_file. The __init__ and get_logger docstrings now say so.
  • deepnote-toolkit server --debug (or -vv) no longer re-creates handlers. Here get_logger(level=level) at cli/server.py:73 matched the import-time DEBUG level, so on main it re-created the handlers. They went to the same path, because the memoized config isn't re-read. With the default level and --quiet the level differs, so this call already returned early. The comments at cli/server.py:61-62 and cli/main.py:54-55 said this call sets up file logging, so that the log directory follows the CLI config. That wasn't true on main either. Importing deepnote_toolkit creates the logger and picks its log file from the config at import time, so a log_dir set through --config never moved it. The second commit rewrites the server.py comment to say the call only sets the level, and removes the main.py note.

Not changed

  • LoggerManager() defaults to level=logging.DEBUG. So a bare LoggerManager() after get_logger(level=X) resets the level to DEBUG, before and after this change. I found this by reading the code; I didn't check whether it happens in a running server.
  • First-time initialization still has no lock. This change doesn't affect it.

Tests

  • test_repeated_get_logger_handles_each_record_once: calls get_logger() twice, logs one ERROR, and checks that the log file holds it once and that report_error_to_webapp is called once.
    • Fails against main's logging.py with AssertionError: 2 != 1.
    • The mock uses autospec=True, so a signature mismatch that WebappErrorHandler.emit would swallow fails the test.
  • test_get_logger_updates_level_after_initialization: guards the level-update branch that the fix moved. It starts at WARNING, lowers to INFO and checks that an INFO line appears, then raises back to WARNING and checks that the next INFO line doesn't. It fails when either the logger's or the handlers' setLevel call is dropped, when self.level isn't updated, or when the condition is narrowed to one direction.
  • TestLoggerManager fixture (third commit): setUp now snapshots os.environ with mock.patch.dict, restores it on cleanup, and pops CI. Before, tearDown and some tests deleted CI from the real environment. GitHub Actions sets CI=true and runs the unit suite in one process, so every test after this class ran with CI unset. A probe test run after the class now sees CI unchanged, whether it started set or unset. Without the pop, the three file-logger tests fail under CI=true.
  • Runs (Python 3.13):
    • tests/unit/test_logging_utils.py: 14 passed, both with and without CI=true.
    • Full unit suite: 1476 passed, 4 skipped, both with and without CI=true. main gives 1474 passed, 4 skipped, with the same 13 warnings.

LoggerManager is a singleton, but __init__ returned early only when the
requested level differed from the current one. Every same-level call ran
_create_logger() and _configure_error_handler() again and added another
file (or stdout) handler and another WebappErrorHandler to the shared
"file_logger" logger.

About ten modules fetch the logger at import time, and
duckdb_sql, variable_explorer and set_notebook_path call it per use, so
a kernel ends up with ten or more copies of each handler and the count
keeps growing. Each record is then written that many times, each ERROR
is reported to the webapp that many times, and every extra FileHandler
holds a file descriptor.

__init__ now returns whenever the manager is initialized, after updating
the level if it changed. log_file is ignored after the first call.
@coderabbitai

coderabbitai Bot commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

LoggerManager now updates the levels of its existing logger and handlers when the level changes after initialization. It does not recreate handlers or change paths in that branch. Documentation states that later log_file values are ignored. Tests cover repeated calls, error reporting, and level filtering. CLI comments now describe import-time logger creation and log-file selection; comments in the main CLI module were removed.

Estimated code review effort: 2 (Simple) | ~10 minutes

Suggested reviewers: m1so

Merge Risk: Minimal · up to 59ea6

This change stops repeated logger retrieval from adding duplicate handlers while still allowing level changes. No actionable merge risk was found.

Pre-merge checks: Passed 5

Check name Status Explanation
Title check Passed The title names the main change: get_logger() calls stop adding log handlers. The changeset makes LoggerManager return early once initialized, which prevents duplicate FileHandler and WebappErrorHandl…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed Description is specific and on-topic. It explains the singleton LoggerManager bug, the duplicate FileHandler and WebappErrorHandler effects with a before/after table, behavior changes (log_file ignore…
Updates Docs Passed The PR is a bug fix (fix(logging): stop adding log handlers on every get_logger() call), not a new feature. The check applies when a feature is implemented, so it does not clearly apply. Docs update…
Full details: Title check

Explanation

The title names the main change: get_logger() calls stop adding log handlers. The changeset makes LoggerManager return early once initialized, which prevents duplicate FileHandler and WebappErrorHandler instances. The title follows the conventional commit format and is specific.

Full details: Description check

Explanation

Description is specific and on-topic. It explains the singleton LoggerManager bug, the duplicate FileHandler and WebappErrorHandler effects with a before/after table, behavior changes (log_file ignored after first call, --debug path), what was not changed, and the tests added and run. It matches the changeset in logging.py, cli/server.py, cli/main.py and tests/unit/test_logging_utils.py.

Full details: Updates Docs

Explanation

The PR is a bug fix (fix(logging): stop adding log handlers on every get_logger() call), not a new feature. The check applies when a feature is implemented, so it does not clearly apply. Docs updated in this repo: - deepnote_toolkit/logging.py: the LoggerManager.__init__ and get_logger docstrings now state that log_file is ignored once the logger is initialized. - deepnote_toolkit/cli/server.py and deepnote_toolkit/cli/main.py: comments were corrected. The main.py note was removed. Other docs: the Deepnote product docs live in the deepnote/deepnote repo. I cannot access that repo from this run. The PR description and CLAUDE.md say user-visible changes need a matching pull request there. This change removes duplicate helpers.log lines and ERROR posts, and it changes log_file behavior. That may be user-visible. Reminder: check whether deepnote/deepnote docs or the roadmap in deepnote/deepnote-internal need an update for the logging behavior change.

Resolution

Not required for PASS. Reminder for the author: verify and, if needed, update the product docs in deepnote/deepnote (docs/) and the roadmap in the private deepnote/deepnote-internal landing page. I could not access those repos.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Essentials
  • Run ID: 7627fe4f-aac8-40ee-bc54-fcda5ce81625
Commits

Reviewing files that changed from the base of the PR and between 5d18cc8 and 59ea696.

Files selected for processing: 1

  • tests/unit/test_logging_utils.py

Included review availability: This review used your included allowance. 1 included review remains after this review. Your included PR review attempts over the past 7 days set your current allowance at 3 reviews per hour.

@github-actions

github-actions Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

📦 Python package built successfully!

  • Version: 2.9.1.dev9+4569052
  • Wheel: deepnote_toolkit-2.9.1.dev9+4569052-py3-none-any.whl
  • Install:
    pip install "deepnote-toolkit @ https://deepnote-staging-runtime-artifactory.s3.amazonaws.com/deepnote-toolkit-packages/2.9.1.dev9%2B4569052/deepnote_toolkit-2.9.1.dev9%2B4569052-py3-none-any.whl"

@codecov

codecov Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 77.77778% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 78.58%. Comparing base (39537e8) to head (59ea696).
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
deepnote_toolkit/logging.py 77.77% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #158      +/-   ##
==========================================
+ Coverage   78.57%   78.58%   +0.01%     
==========================================
  Files         121      121              
  Lines        6935     6936       +1     
  Branches     1009     1010       +1     
==========================================
+ Hits         5449     5451       +2     
  Misses       1179     1179              
+ Partials      307      306       -1     
Flag Coverage Δ
combined 78.58% <77.77%> (+0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

@deepnote-bot

deepnote-bot commented Dec 4, 2026 •

Copy link
Copy Markdown

🚀 Review App Deployment Started

📝 Description 🌐 Link / Info
🌍 Review application ra-158
🔑 Sign-in URL Click to sign-in
📊 Application logs View logs
🔄 Actions Click to redeploy
🚀 ArgoCD deployment View deployment
⏰ Last deployed 2026-12-04 17:13:25 (UTC)
📜 Deployed commit 499aa33ff3ef8b41749ada6c864101eba8442843
🛠️ Toolkit version 4569052

The server command's get_logger(level=level) call never set up file
logging. Importing deepnote_toolkit has already created the logger and
picked its log file from the config at import time, so the call only
sets the level, and a log_dir from --config doesn't move the log file.
@tkislan

tkislan commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor
Action performed

Full review finished.

@tkislan

tkislan commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 4, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-04T14:00:21.362826Z 5d18cc8 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: 5d18cc8b60

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

coderabbitai[bot]
coderabbitai Bot previously approved these changes Dec 4, 2026
@tkislan
tkislan marked this pull request as ready for review December 4, 2026 14:16
@tkislan
tkislan requested a review from a team as a code owner December 4, 2026 14:16
@tkislan
tkislan requested review from m1so and mfranczel December 4, 2026 14:16
m1so
m1so previously approved these changes Dec 4, 2026

@m1so m1so left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@tkislan LGTM, nice find ✅

minor improvement would be to clean up the TestCase's handling of os.environ as we're now mutating it for other tests, though this pattern might have been pre-existing

TestLoggerManager deleted CI from the real environment in tearDown and
in individual tests, and never restored it. GitHub Actions sets CI=true
and runs the unit suite in one process, so every test after this class
ran with CI unset, which switches the toolkit logger from stdout to a
file and adds the webapp error handler.

setUp now snapshots os.environ with mock.patch.dict and restores it on
cleanup, and pops CI once so the tests start outside CI. The per-test
and tearDown deletions go.
@tkislan
tkislan dismissed stale reviews from m1so and coderabbitai[bot] via 59ea696 December 4, 2026 16:59
@tkislan

tkislan commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

@m1so it was just a small change, so I just reused a proper test setup from other test

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants